package cn.bye.lyu.boot.server.config;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import cn.bye.lyu.boot.interceptor.MyInterceptor;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	public final static Logger LOG = LoggerFactory.getLogger(WebMvcConfig.class);

	/**
	 * 配置静态访问资源
	 *
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		LOG.info("====>添加静态资源映射( {} ) ", registry.getClass().getName());
		registry.addResourceHandler("/lyu/**").addResourceLocations("classpath:/lyu/");
		super.addResourceHandlers(registry);
	}

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		LOG.info("===>添加视图控制器（{}）", registry.getClass().getSimpleName());
		registry.addViewController("/toLogin").setViewName("login");
		super.addViewControllers(registry);
	}
	
	/**
     *拦截器 
     *
     *本例中addPathPatterns("/**")对所有请求都拦截，但是排除了/toLogin和/login请求的拦截。
     *
     *@param registry
     */
	@Override
    public void addInterceptors(InterceptorRegistry registry){
    	LOG.info("====>添加拦截器（{}）",registry.getClass().getSimpleName());
    	registry.addInterceptor(new MyInterceptor())
    			.addPathPatterns("/**")  //用于添加拦截规则
    			.excludePathPatterns("/toLogin","/login");	//用户排除拦截
    	super.addInterceptors(registry);
    }
    /**
     * 配置fastJson
     * 
     *@param converters
     *@author luliangwei
     *
     */
	public void messageConverters(List<HttpMessageConverter<?>> converters){
    	FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    	FastJsonConfig fastJsonConfig = new FastJsonConfig();
    	fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    	converters.add(fastConverter);
    	super.configureMessageConverters(converters);
    }
}
